package org.example.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.example.annotation.RedisLimit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
@Aspect
public class RedisLimitAop {
    @Pointcut("@annotation(org.example.annotation.RedisLimit)")
    private void check(){
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private DefaultRedisScript<Long> redisScript;

    @PostConstruct
    public void init(){
        redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("rateLimiter.lua")));
    }

    @Before("check()")
    public void before(JoinPoint joinPoint){
        System.out.print("addrr");
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();

        RedisLimit redisLimit = method.getAnnotation(RedisLimit.class);
        if(redisLimit!=null){
            String key = redisLimit.key();
            String methodName = method.getName();
            key = key + ":" + methodName;

            long limitCount= redisLimit.permitsPerSecond();
            long expireTime = redisLimit.expire();
            List<String> keys = new ArrayList<>();
            keys.add(key);

            Long count = stringRedisTemplate.execute(redisScript, keys, String.valueOf(limitCount), String.valueOf(expireTime));
            log.info("Access try count is {} for key={}", count, key);

            if(count!=null && count==0){
                log.debug("获取key失败，key为{}", key);
                throw new RuntimeException(redisLimit.msg());
            }
        }
    }
}
